package com.example;

import com.example.config.AppConfig;
import com.example.service.TaskService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 应用主类
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 初始化Spring上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // 获取线程池和任务服务
        ThreadPoolExecutor executor = context.getBean("taskExecutor", ThreadPoolExecutor.class);
        TaskService taskService = context.getBean(TaskService.class);

        System.out.println("线程池初始化完成，核心线程数: " + executor.getCorePoolSize());

        try {
            // 查找并提交所有带有@Task注解的方法
            Method[] methods = TaskService.class.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(com.example.annotation.Task.class)) {
                    String taskName = method.getAnnotation(com.example.annotation.Task.class).name();
                    System.out.println("提交任务: " + (taskName.isEmpty() ? method.getName() : taskName));

                    // 提交任务到线程池
                    executor.submit(() -> {
                        try {
                            method.invoke(taskService);
                        } catch (Exception e) {
                            System.err.println("任务执行出错: " + e.getMessage());
                        }
                    });

                    // 稍微延迟一下，让任务输出顺序更清晰
                    Thread.sleep(500);
                }
            }
        } finally {
            // 等待所有任务完成后关闭线程池和上下文
            executor.shutdown();
            // 等待所有任务完成
            if (executor.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES)) {
                System.out.println("所有任务已完成");
            } else {
                System.out.println("等待超时，可能还有任务未完成");
                // 强制关闭
                executor.shutdownNow();
            }
            context.close();
        }
    }
}
